package com.ctg.payroll2.action.payment;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.greentea.expression.format.FormatException;

import com.ctg.payroll2.action.BaseAction;
import com.ctg.payroll2.bean.filter.payment.PayClazzItemFilter;
import com.ctg.payroll2.bean.po.payment.PayClassitem;
import com.ctg.payroll2.bean.po.payment.PayClassitemLimitDate;
import com.ctg.payroll2.service.payment.PayClazzItemService;
import com.ctg.payroll2.util.Constants;
import com.ctg.platform.util.Page;
import com.ctg.platform.util.Parse;

public class PayClassItemAction extends BaseAction {
	private static final long serialVersionUID = 1L;

	private int flag;

	/**
	 * 页面过滤条件
	 */
	private PayClazzItemFilter filter;

	/**
	 * 修改和更新需要的实体
	 */
	private PayClassitem payClassitem;

	/**
	 * 注入的service
	 */
	private PayClazzItemService service;

	/**
	 * 时间限制的list
	 */
	private List<PayClassitemLimitDate> limitList;

	private List<PayClassitem> list;

	private String msg;
	private String msg1;

	/**
	 * grid显示内容
	 */
	private Page result;

	@Override
	protected void commonOperations() {
	}

	@Override
	protected void createEntity() {
		createPayItem();
	}

	@Override
	protected void deleteEntity() {
		try {
			service.deletePayItemByIds(filter.getIds());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void updateEntity() throws Exception {
		switch (flag) {
		case 1:// 只更新是否显示和是否有效
			updateValidAndDisplay();
			break;
		case 2:// 更新所有字段
			updatePayOption();
			break;
		default:
			break;
		}
	}

	@Override
	protected void queryEntity() {
		switch (flag) {
		case 1:// 薪资项目的翻页查询
			result = getPayItemListByFilter();
			break;
		case 2:// 时间限制的查询
			limitList = getPayClassitemLimitDateList();
			break;
		case 3:// 显示顺序的查询
			list = getDisplayPayItemListByFilter();
			break;
		default:
			break;
		}
	}

	@Override
	protected void retrieveEntity() {
		switch (flag) {
		case 1:
			payClassitem = service.queryPayItemByFilter(filter).get(0);
			String str = payClassitem.getData_come();
			str = str == null ? "-1" : str;
			switch (Integer.parseInt(str)) {
			case 0:
				payClassitem.setFixedData(payClassitem.getSegment1());
				break;
			case 4:
				payClassitem.setLastMonth(payClassitem.getSegment1());
				break;
			case 9:
				payClassitem.setOther(payClassitem.getSegment1());
				break;
			case 3:
				payClassitem.setFormula(payClassitem.getSegment1());
				break;
			case 1:
				// payClassitem.setSegment1(payClassitem.getFormula());
				break;
			default:
				break;
			}
			break;
		case 2:
			System.out.println(filter.getIds());
			try {
				msg1 = service.checkExistsInFormula(filter.getIds());
				msg = service.checkExistsInHis(filter.getIds());
			} catch (SQLException e) {
				e.printStackTrace();
			}
			break;
		case 3://判断薪资项目名是否重复
			try {
				msg = service.checkItemIsValid(filter);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			break;
		}
	}

	private void createPayItem() {
		String modified = request.getParameter("modified");
		List<PayClassitemLimitDate> modifieds = new ArrayList<PayClassitemLimitDate>();
		JSONArray modifiedArray = JSONArray.fromObject(modified);
		for (int i = 0; i < modifiedArray.size(); i++) {
			Object o = modifiedArray.get(i);
			JSONObject jsonObject = JSONObject.fromObject(o);
			PayClassitemLimitDate payClassitemLimitDate = (PayClassitemLimitDate) JSONObject
					.toBean(jsonObject, PayClassitemLimitDate.class);
			modifieds.add(payClassitemLimitDate);
		}
		payClassitem.setDetailList(modifieds);
		String str = payClassitem.getData_come();
		str = str == null ? "-1" : str;
		switch (Integer.parseInt(str)) {
		case 0:
			payClassitem.setSegment1(payClassitem.getFixedData());
			break;
		case 4:
			payClassitem.setSegment1(payClassitem.getLastMonth());
			break;
		case 9:
			payClassitem.setSegment1(payClassitem.getOther());
			break;
		case 3:
			try {
					payClassitem.setFormula_tmp2(com.ctg.salary.util.VariableTokenUtils.AnalyzeVariables(payClassitem.getSegment1()));
				} catch (IOException e) {
					e.printStackTrace();
				} catch (FormatException e) {
					e.printStackTrace();
				}
			break;
		case 1:
			// payClassitem.setSegment1(payClassitem.getFormula());
			break;
		case 2:
			// payClassitem.setSegment1(payClassitem.getFormula());
			break;
		default:
			break;
		}
		payClassitem.setCreator_code(currentUser.getEmployeeCsCode());
		payClassitem.setCompany_code(currentUser.getCompanyCode());
		Long id=service.insertPayItem(payClassitem);
		if(payClassitem.getSegment_order()==null||payClassitem.getSegment_order().equals("")){
			Integer segmentOrder=service.getNextSegmentOrder(payClassitem);
			if(segmentOrder<255){
				payClassitem.setSegment_order(segmentOrder);
			}else{
				msg = "薪资项目总数不能超过205个";
				return;
			}
			service.modifyPayItem(payClassitem);
		}
		switch (Integer.parseInt(str)) {
		case 1:
			payClassitem.setSegment1(id.toString());
			service.modifyPayItem(payClassitem);
			break;
		default:
			break;
		}
	}

	/**
	 * 薪资类别的翻页查询
	 * 
	 * @return
	 */
	private Page getPayItemListByFilter() {
		if (filter == null) {
			filter = new PayClazzItemFilter();
		}
		filter.setStartIndex(Parse.toInteger(request.getParameter("start"), 0));
		filter.setEndIndex(Parse.toInteger(request.getParameter("limit"),
				Constants.DEFAULT_PAGE_SIZE));
		result = service.getPayItemListByFilter(filter);
		return result;

	}

	/**
	 * 薪资类别的显示顺序翻页查询
	 * 
	 * @return
	 */
	private List<PayClassitem> getDisplayPayItemListByFilter() {
		if (filter == null) {
			filter = new PayClazzItemFilter();
		}
		return service.getDisplayPayItemListByFilter(filter);

	}
	
	private void updateValidAndDisplay() throws Exception {
		if(payClassitem.getIs_valid()==null){
			service.updateValidAndDisplay(payClassitem);
		}else{
			payClassitem.setName1("$"+payClassitem.getName()+"$");
			if (service.validateValidAndDisplay(payClassitem) <= 0) {
				service.updateValidAndDisplay(payClassitem);
			}else{
				throw new Exception();
			}
		}
	}

	private void updatePayOption() {
		String modified = request.getParameter("modified");
		List<PayClassitemLimitDate> modifieds = new ArrayList<PayClassitemLimitDate>();
		JSONArray modifiedArray = JSONArray.fromObject(modified);
		for (int i = 0; i < modifiedArray.size(); i++) {
			Object o = modifiedArray.get(i);
			JSONObject jsonObject = JSONObject.fromObject(o);
			PayClassitemLimitDate payClassitemLimitDate = (PayClassitemLimitDate) JSONObject
					.toBean(jsonObject, PayClassitemLimitDate.class);
			modifieds.add(payClassitemLimitDate);
		}
		payClassitem.setDetailList(modifieds);
		String str = payClassitem.getData_come();
		str = str == null ? "-1" : str;
		switch (Integer.parseInt(str)) {
		case 0:
			payClassitem.setSegment1(payClassitem.getFixedData());
			break;
		case 4:
			payClassitem.setSegment1(payClassitem.getLastMonth());
			break;
		case 9:
			payClassitem.setSegment1(payClassitem.getOther());
			break;
		case 3:
			try {
				payClassitem.setFormula_tmp2(com.ctg.salary.util.VariableTokenUtils.AnalyzeVariables(payClassitem.getSegment1()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case 1:
			// payClassitem.setSegment1(payClassitem.getFormula());
			break;
		case 2:
			// payClassitem.setSegment1(payClassitem.getFormula());
			break;
		default:
			break;
		}
		payClassitem.setCompany_code(currentUser.getCompanyCode());
		payClassitem.setCreator_code(currentUser.getEmployeeCsCode());
		service.modifyPayItem(payClassitem);
	}

	@SuppressWarnings("unchecked")
	public String queryClassitemForFormula() {
		list = service.queryForFormula(payClassitem);
		return SUCCESS;
	}

	private List<PayClassitemLimitDate> getPayClassitemLimitDateList() {
		return service.getTimeLimitByPayItemId(filter.getPayItemId());
	}

	/**
	 * @param service
	 *            设置service
	 */
	public void setService(PayClazzItemService service) {
		this.service = service;
		logger
				.debug("service注入<"
						+ service.getClass().getInterfaces()[0].getSimpleName()
						+ ">成功");
	}

	/**
	 * @return 返回filter
	 */
	public PayClazzItemFilter getFilter() {
		return filter;
	}

	/**
	 * @param filter
	 *            设置filter
	 */
	public void setFilter(PayClazzItemFilter filter) {
		this.filter = filter;
	}

	/**
	 * @return 返回result
	 */
	public Page getResult() {
		return result;
	}

	/**
	 * @param result
	 *            设置result
	 */
	public void setResult(Page result) {
		this.result = result;
	}

	/**
	 * @return 返回payClassitem
	 */
	public PayClassitem getPayClassitem() {
		return payClassitem;
	}

	/**
	 * @param payClassitem
	 *            设置payClassitem
	 */
	public void setPayClassitem(PayClassitem payClassitem) {
		this.payClassitem = payClassitem;
	}

	/**
	 * @return 返回flag
	 */
	public int getFlag() {
		return flag;
	}

	/**
	 * @param flag
	 *            设置flag
	 */
	public void setFlag(int flag) {
		this.flag = flag;
	}

	/**
	 * @return 返回limitList
	 */
	public List<PayClassitemLimitDate> getLimitList() {
		return limitList;
	}

	/**
	 * @param limitList
	 *            设置limitList
	 */
	public void setLimitList(List<PayClassitemLimitDate> limitList) {
		this.limitList = limitList;
	}

	@Override
	protected void exportXLS() {
	}

	public List<PayClassitem> getList() {
		return list;
	}

	public void setList(List<PayClassitem> list) {
		this.list = list;
	}

	/**
	 * @return 返回msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @param msg
	 *            设置msg
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getMsg1() {
		return msg1;
	}

	public void setMsg1(String msg1) {
		this.msg1 = msg1;
	}

}
